﻿using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using SwParaPlatform2.logger;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SwParaPlatform2.dlgSubPage
{
    public partial class dlgRename : UserControl
    {
        private readonly ISwParaInterface _commonInterface;
        private ISldWorks iSwApp;
        public Dictionary<string, object> dNestDict;
        private Dictionary<string, object> dNote_NameData;
        public event Action OpenWindowBtnClick;
        public event Action SaveFileBtnClick;
        public event Action ShowMainForm;

        public dlgRename(ISldWorks SwApp)
        {
            iSwApp = SwApp;
            InitializeComponent();
            RefreshTreeView();
            _commonInterface = new SwParaInterface();
            dNestDict = new Dictionary<string, object>();
            dNote_NameData = DataStore.Instance.dNote_NameData;
            this.Dock = DockStyle.Top;
            // 禁止收起节点
            treeView1.BeforeCollapse += TreeView_BeforeCollapse;
        }

        public void ClearData()
        {
            dNestDict = new Dictionary<string, object>();
            dNote_NameData = new Dictionary<string, object>();
            RefreshTreeView();
        }

        public void OnSelectElement(List<string> lSearchList)
        {
            dNestDict = _commonInterface.GetNestedDictionary(DataStore.Instance.TreeViewData, lSearchList);
            dNestDict["Title"] = lSearchList[lSearchList.Count - 1];
            RefreshSelectDict();
        }

        public void RefreshSelectDict()
        {
            if (dNestDict.TryGetValue("sName", out var sElementName))
            {
                PropNameInput.Text = (string)sElementName;
            }
            else
            {
                PropNameInput.Text = "获取名称失败";
            }

            if (dNestDict.TryGetValue("TempName", out var sTempName))
            {
                NoteInput.Text = (string)sTempName;
            }
            else
            {
                NoteInput.Text = "";
            }
            // _commonInterface.PrintDictionary(dNestDict, 0);
        }

        #region 节点树
        public void RefreshTreeView()
        {
            TreeBuilder builder = new TreeBuilder();
            treeView1.Nodes.Clear();
            var mainMainSubComp = DataStore.Instance.GetMainMainSubComp(DataStore.Instance.TreeViewData);

            if (mainMainSubComp != null)
            {
                foreach (var subComp in mainMainSubComp)
                {
                    Dictionary<string, object> dSubChildComp = (Dictionary<string, object>)subComp.Value;
                    string sChildTreeName;
                    if(dSubChildComp.TryGetValue("TempName", out var sTempName))
                    {
                        sChildTreeName = (string)sTempName;
                    }
                    else
                    {
                        sChildTreeName = subComp.Key;
                    }
                    
                    DataTreeNode rootNode = builder.CreateNodeTree((Dictionary<string, object>)subComp.Value, sChildTreeName);
                    if(rootNode != null)
                    {
                        Logger.Instance.Log($"subkey     {sChildTreeName}     {rootNode.Children.Count}");
                        if (rootNode.Children.Count > 0)
                        {
                            AddNodesToTreeView(treeView1, rootNode);
                        }
                    }
                    
                    
                }

                // 展开所有节点
                ExpandAllNodes(treeView1.Nodes);
            }
        }

        public void AddNodesToTreeView(TreeView treeView, DataTreeNode node, bool isRoot = true)
        {
            var treeNode = new System.Windows.Forms.TreeNode(node.Name)
            {
                Tag = node.Data
            };

            if (isRoot)
            {
                // 设置根节点为灰色，并且不可选
                treeNode.ForeColor = Color.Gray;
                treeNode.NodeFont = new Font(treeView.Font, FontStyle.Italic);
            }

            foreach (var child in node.Children)
            {
                AddNodesToTreeNode(treeNode, child, false);
            }

            treeView.Nodes.Add(treeNode);
        }

        private void AddNodesToTreeNode(System.Windows.Forms.TreeNode parentTreeNode, DataTreeNode node, bool isRoot = false)
        {
            var treeNode = new System.Windows.Forms.TreeNode(node.Name)
            {
                Tag = node.Data
            };

            foreach (var child in node.Children)
            {
                AddNodesToTreeNode(treeNode, child, false);
            }

            parentTreeNode.Nodes.Add(treeNode);
        }

        // 递归展开所有节点
        private void ExpandAllNodes(TreeNodeCollection nodes)
        {
            foreach (TreeNode node in nodes)
            {
                node.Expand();
                ExpandAllNodes(node.Nodes); // 递归展开子节点
            }
        }

        // 取消节点收起操作
        private void TreeView_BeforeCollapse(object sender, TreeViewCancelEventArgs e)
        {
            e.Cancel = true; // 取消收起操作
        }
        #endregion

        public void SavaConfig(bool Pack=true)
        {
            try
            {
                Dictionary<string, object> dName_NoteData = _commonInterface.ReverseDictionary(dNote_NameData);
                string filePath = XmlHandler.GetFilePath();
                DataStore.Instance.SaveNameNoteData(dNote_NameData, dName_NoteData);

                if (Pack)
                {
                    int errors = 0;
                    int warnings = 0;
                    ModelDoc2 ActiveDoc = iSwApp.ActiveDoc;
                    string DocPath = ActiveDoc.GetPathName();
                    int iDocType = ActiveDoc.GetType();
                    iSwApp.CloseDoc(ActiveDoc.GetTitle());

                    XmlHandler.SaveAndPackConfigFile(filePath, DataStore.Instance.dNote_NameData_Pack, Defines.Note_NameElementName);
                    XmlHandler.SaveAndPackConfigFile(filePath, DataStore.Instance.dName_NoteData_Pack, Defines.Name_NoteElementName);
                    
                    IModelDoc2 modelDoc = iSwApp.OpenDoc6(DocPath, iDocType,
                    (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.Log($"Error in SavaConfig: {ex.Message}");
                Logger.Instance.Log($"Stack Trace: {ex.StackTrace}");
            }

        }

        private void ShowToolTip(Control control, string message)
        {
            ToolTip toolTip = new ToolTip();
            toolTip.IsBalloon = true;
            toolTip.Show(message, control, 0, -50, 2000); // 在控件上方显示，持续3秒
        }

        public void OnCatchFail(string sTips)
        {
            ShowToolTip(PropNameInput, sTips);
        }

        private void SaveNoteBtn_Click(object sender, EventArgs e)
        {
            string sNote = NoteInput.Text;
            var result = XmlHandler.ValidateElementName(sNote, "备注");
            if (!result.IsValid)
            {
                ShowToolTip(NoteInput, $"设置备注名失败。{result.ViolationReason}");
                return;
            }

            DelKeyByTitle((string)dNestDict["Title"]);

            if (dNote_NameData.ContainsKey(sNote))
            {
                MessageBox.Show($"备注{sNote}已存在！");
                return;
            }
            dNestDict["TempName"] = sNote;
            dNote_NameData[sNote] = (string)dNestDict["Title"];
            RefreshTreeView();
        }

        private void DelKeyByTitle(string sTitle)
        {
            foreach (var kvp in new List<KeyValuePair<string, object>>(dNote_NameData))
            {
                if ((string)kvp.Value == sTitle)
                {
                    dNote_NameData.Remove(kvp.Key);
                    Logger.Instance.Log($"已删除键值对：{kvp.Key}: {kvp.Value}");
                }
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.ForeColor != Color.Gray)
            {
                // 打印选中节点对应的字典内容
                Dictionary<string, object> data = e.Node.Tag as Dictionary<string, object>;
                if (data != null)
                {
                    dNestDict = data;
                    RefreshSelectDict();
                }
            }
            else
            {
                // 如果是灰色节点，取消选择
                treeView1.SelectedNode = null;
            }
        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            SaveFileBtnClick.Invoke();
        }

        private void OpenBtn_Click(object sender, EventArgs e)
        {
            //SavaConfig();
            OpenWindowBtnClick?.Invoke();
        }

        private void BackBtn_Click(object sender, EventArgs e)
        {
               ShowMainForm?.Invoke();
        }

        private void NoteInput_TextChanged(object sender, EventArgs e)
        {

        }

        private void DelNoteBtn_Click(object sender, EventArgs e)
        {
            string sNote = NoteInput.Text;
            string sTitle = (string)dNote_NameData[sNote];
            dNote_NameData.Remove(sNote);

            var mainMainSubComp = DataStore.Instance.GetMainMainSubComp(DataStore.Instance.TreeViewData);

            if (mainMainSubComp != null)
            {
                foreach (var subComp in mainMainSubComp)
                {
                    Dictionary<string, object> dSubChildComp = (Dictionary<string, object>)subComp.Value;
                    Dictionary<string, object> dSubGrandChildComp = (Dictionary<string, object>)dSubChildComp["SubComp"];
                    foreach(var oKvp in dSubGrandChildComp)
                    {
                        string sKvpKey = oKvp.Key;
                        if(sTitle == sKvpKey)
                        {
                            Dictionary<string, object> dKvpValue = (Dictionary<string, object>)oKvp.Value;
                            dKvpValue["TempName"] = null;
                        }
                    }
                }
            }
            RefreshTreeView();
        }
    }
}
